package com.lgrglw.common.spring;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author 李伟 E-mail:010420420@163.com
 * @version 创建时间：Mar 27, 2013 2:38:37 PM 自动获取bean
 */
public class SpringAppContentAware implements ApplicationContextAware {

	private final static Logger log = LoggerFactory
			.getLogger(SpringAppContentAware.class);

	private static ApplicationContext applicationContext;

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringAppContentAware.applicationContext = applicationContext;
	}

	/**
	 * 通过spring上下文直接获取bean 当bean不存在时会抛出异常
	 * 
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		Object bean = applicationContext.getBean(name);
		return bean;
	}

	/**
	 * 获取项目的根路径
	 * 
	 * @return
	 */
	public static String getBasePath() {
		String path = "";
		try {
			path = applicationContext.getResource("").getFile()
					.getAbsolutePath();
		} catch (IOException e) {
			log.error("获取项目根路径出错了!", e);
		}
		return path;
	}

}
